package com.jie.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.jie.annotation.OptLog;
import com.jie.dto.UserBackDTO;
import com.jie.dto.UserDetailDTO;
import com.jie.dto.UserLoginParam;
import com.jie.entity.UserInfo;
import com.jie.response.RespBean;
import com.jie.service.UserInfoService;
import com.jie.vo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;

import static com.jie.constants.OptTypeConst.UPDATE;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author zwq
 * @since 2022-01-04
 */
@Slf4j
@RestController
@Api(tags = "用户模块")
public class UserInfoController {

    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    private DefaultKaptcha defaultKaptcha;


    @ApiOperation(value = "注册接口")
    @PostMapping("/register")
    public RespBean<?> register(@Valid @RequestBody UserRegisterVO userRegisterVO) {
        return userInfoService.register(userRegisterVO);
    }

    /**
     * 登录之后返回Token
     *
     * @param adminLoginParam
     * @param request
     * @return
     */
    @ApiOperation(value = "后台登录")
    @PostMapping("/login")
    public RespBean<?> login(@RequestBody UserLoginParam adminLoginParam, HttpServletRequest request) {
        return userInfoService.login(adminLoginParam.getUsername(), adminLoginParam.getPassword(), adminLoginParam.getCode(), request);
    }

    @ApiOperation(value = "APP登录")
    @PostMapping("/loginAPP")
    public RespBean<?> loginApp(@RequestBody UserLoginParam adminLoginParam, HttpServletRequest request) {
        return RespBean.success("appLogin", userInfoService.loginApp(adminLoginParam.getUsername(), adminLoginParam.getPassword(), request));
    }

    @ApiOperation(value = "获取当前登录用户的信息")
    @GetMapping("/admin/info")
    public RespBean<UserDetailDTO> getAdminInfo() {
        UserDetailDTO admin = userInfoService.getAdminByUserName();
        return RespBean.success("用户信息", admin);
    }

    @ApiOperation(value = "退出登录")
    @GetMapping("/logout")
    public RespBean<?> logout() {
        userInfoService.logout();
        return RespBean.success("注销成功!");
    }

    @ApiOperation(value = "验证码")
    @GetMapping(value = "/captcha", produces = "image/jpeg")
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        //定义response输出类型为image/jpeg类型
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store,no-cache,must-revalidate");
        response.addHeader("Cache-Control", "post-check=0,pre-check=0");
        response.setContentType("image/jpeg");
        //生成验证码
        String text = defaultKaptcha.createText();
        HttpSession session = request.getSession();
        session.setAttribute("captcha", text);
        log.info("验证码" + text);
        //根据文本验证码内容得到图片
        BufferedImage image = defaultKaptcha.createImage(text);
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            //输出流输出图片
            ImageIO.write(image, "jpg", outputStream);
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    /**
     * 注册账户
     */
    @OptLog(optType = UPDATE)
    @ApiOperation(value = "修改用户权限")
    @PutMapping("/role")
    public RespBean<?> updateUserRole(@Valid @RequestBody UserRoleVO userRoleVO) {
        userInfoService.updateUserRole(userRoleVO);
        return RespBean.success();
    }

    @ApiOperation("根据用户id获取用户信息")
    @GetMapping("/getUserInfoById")
    public RespBean<?> getUserInfoById(Integer id) {
        UserInfo userInfo = userInfoService.getById(id);
        return RespBean.success("userinfo", userInfo);
    }

    @ApiOperation(value = "用户修改密码")
    @PutMapping("/updateUserPassword")
    public RespBean<?> updateUserPassword(String password) {
        userInfoService.updateUserPassword(password);
        return RespBean.success("修改成功");
    }

    @ApiOperation("后台统计接口未完成")
    @GetMapping("/user-info/getStatistics")
    public RespBean<?> statistics() {
        return RespBean.success("后台统计", null);
    }

    /**
     * 查询后台用户列表
     *
     * @param condition 条件
     * @return 用户列表
     */
    @ApiOperation(value = "查询后台用户列表")
    @GetMapping("/users")
    public RespBean<UserBackDTO> listUsers(ConditionVO condition) {
        return RespBean.success("用户列表", userInfoService.listUserBackDTO(condition));
    }

    @ApiOperation("QQ邮箱发送验证码")
    @PostMapping("qq-email/send-code")
    public RespBean<?> qqEmailSendCode(@Valid @RequestBody QQEmailVO qqEmailVO) {
        boolean flag = userInfoService.emailSendCode(qqEmailVO);
        return RespBean.success("发送成功", flag);
    }

    @ApiOperation(value = "QQ邮箱注册用户")
    @PostMapping("qq-email/register")
    public RespBean<?> qqEmailRegister(@Valid @RequestBody QQEmailRegisterLoginVO qqEmailRegisterLoginVO) {
        boolean flag = userInfoService.qqEmailRegister(qqEmailRegisterLoginVO);
        return RespBean.success("注册成功", flag);
    }

    @ApiOperation(value = "QQ邮箱登录")
    @PostMapping("qq-email/login")
    public RespBean<?> qqEmailLogin(@Valid @RequestBody QQEmailRegisterLoginVO qqEmailRegisterLoginVO) {

        return RespBean.success("登录成功", null);
    }

    @ApiOperation(value = "刷新Token")
    @GetMapping("refreshToken")
    public RespBean<?> refreshToken(@RequestParam("token") String token) {
        HashMap<String, String> tokenMap = userInfoService.refreshToken(token);
        return RespBean.success("刷新Token成功", tokenMap);
    }
}

